<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Scroll Demo</title>
  </head>

  <body>
    <style>
      .box {
        height: 500px;
		width: 50%;
        text-align: center;
		background: red;
		border: 1px solid #000;
      }
    </style>

    <div class="box" id="box">打开控制台查看</div>
	<div class="box" id="box" style="background: yellow;">打开控制台查看</div>
	<div class="box" id="box" style="background: blue;">打开控制台查看</div>
    <!-- 引入节流方法 -->
    <script src="https://cdn.jsdelivr.net/npm/throttle-debounce@5.0.0/umd/index.min.js"></script>

    <script>
      // 滚动方向枚举值
      const DIRECTION_ENUM = {
        DOWN: "down",
        UP: "up",
      };

      // 距离顶部或底部的阈值
      const threshold = 20;

      // 记录前一个滚动位置
      let beforeScrollTop = 0;

      function handleScroll() {
        // 距顶部
        var scrollTop =
          document.documentElement.scrollTop || document.body.scrollTop;
        // 可视区高度
        var clientHeight =
          document.documentElement.clientHeight || document.body.clientHeight;
        // 滚动条总高度
        var scrollHeight =
          document.documentElement.scrollHeight || document.body.scrollHeight;
		console.log("距顶部:",scrollTop,"--可视区高度",clientHeight,"--滚动条总高度:",scrollHeight,"--距顶部 + 可视区高度:",scrollTop + clientHeight)
        // 打印数值
        // console.table([
        //   {
        //     label: "距顶部",
        //     value: scrollTop,
        //   },
        //   {
        //     label: "可视区高度",
        //     value: clientHeight,
        //   },
        //   {
        //     label: "滚动条总高度",
        //     value: scrollHeight,
        //   },
        //   {
        //     label: "距顶部 + 可视区高度",
        //     value: scrollTop + clientHeight,
        //   },
        // ]);

        // 确定滚动方向
        let direction = DIRECTION_ENUM.DOWN;
        if (beforeScrollTop > scrollTop) {
          direction = DIRECTION_ENUM.UP;
        }

        // 通过滚动方向判断是触底还是触顶
        if (direction == DIRECTION_ENUM.DOWN) {
          // 滚动触底
          if (scrollTop + clientHeight + threshold >= scrollHeight) {
            console.log("滚动触底");
          }
        } else {
          // 滚动到顶部
          if (scrollTop <= threshold) {
            console.log("滚动到顶部");
          }
        }

        beforeScrollTop = scrollTop;
      }

      // 滚动节流
      const throttleHandleScroll = throttleDebounce.throttle(
        1000,
        handleScroll
      );

      // 监听滚动
      window.addEventListener('scroll', throttleHandleScroll);

    </script>
  </body>
</html>